<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class SelfOrderIndex extends AdminController{
	public $_validation = null;
	
	function __construct(){
	    date_default_timezone_set('Asia/Shanghai');
		parent::__construct();
		$this->load->model('MSelfBankOrder');
		$this->load->model('MOrder');
		$this->pay_status_css = array(
				'0'=>'label label-sm label-default',
				'1'=>'label label-sm label-success'
		);
		$this->transfer_status_css = array(
				'0'=>'label label-sm label-default',
				'1'=>'label label-sm label-success',
				'2'=>'label label-sm label-warning'
		);
		$this->_validation = Array(
			array('field'=>'no', 'label'=>'订单号', 'rules'=>'required|max_length[16]')
			,array('field'=>'user_id', 'label'=>'用户编号', 'rules'=>'required|integer|max_length[11]')
			,array('field'=>'amount', 'label'=>'订单数量', 'rules'=>'required')
			,array('field'=>'pay_status', 'label'=>'自有通道状态', 'rules'=>'integer')
			,array('field'=>'pay_time', 'label'=>'自有通道确认时间', 'rules'=>'integer')
			,array('field'=>'pay_channel', 'label'=>'自有通道', 'rules'=>'max_length[32]')
			,array('field'=>'pay_transaction', 'label'=>'自有通道流水号', 'rules'=>'max_length[32]')
			,array('field'=>'transfer_platform', 'label'=>'平台', 'rules'=>'max_length[32]')
			,array('field'=>'transfer_status', 'label'=>'平台状态', 'rules'=>'integer|max_length[4]')
			,array('field'=>'transfer_time', 'label'=>'平台确认时间', 'rules'=>'integer')
			,array('field'=>'update_time', 'label'=>'更新时间', 'rules'=>'')
		);
	}
	/**
	 * 手工订单列表
	 * @param unknown $game_tag
	 */
	function index($game_tag=null){
		//$this->output->enable_profiler(TRUE);
		//$this->load->model('MUser');
		$this->load->library('FormFilter');
		$this->load->helper('formfilter');
		$this->formfilter->addFilter('no', 'where');
		$this->formfilter->addFilter('user_id','where');
		$this->formfilter->addFilter('user.account','where');
		$this->formfilter->addFilter('pay_status','where');
		$this->formfilter->addFilter('transfer_status','where');
		
		$limit = $this->pagination($this->MOrder->getCount(TRUE));
		$list = $this->MOrder->getList($limit,TRUE);
		$this->assign('list', $list);
		$this->layout();
	}
	
	function add(){
	    $this->load->helper('populate');
	    $obj = $this->MSelfBankOrder->createVo();
	    if($this->input->get()){
	        $obj = populate((Object)((Array)$obj), $this->input->get());
	    }
	    
	    $this->load->library('form_validation');
	    $this->form_validation->set_rules(array(
	        array('field'=>'account', 'label'=>'用户账号', 'rules'=>'trim|required|numeric|exact_length[11]|callback__checkAccount'),
	        array('field'=>'amount', 'label'=>'数量', 'rules'=>'required|numeric'),
	        array('field'=>'percet', 'label'=>'优惠比例', 'rules'=>''),
	        array('field'=>'recharge_amount', 'label'=>'优惠后数量', 'rules'=>'required'),
	        array('field'=>'bank_code', 'label'=>'自有通道编号', 'rules'=>'required|callback__checkBankCode'),
	        array('field'=>'pay_transaction', 'label'=>'自有通道流水号', 'rules'=>'required'),
	        array('field'=>'payer_name', 'label'=>'用户姓名', 'rules'=>'required'),
	        array('field'=>'bank_account', 'label'=>'用户通道帐户', 'rules'=>'required'),
	        array('field'=>'pay_time', 'label'=>'自有通道确认时间', 'rules'=>'required'),
	        array('field'=>'update_time', 'label'=>'更新时间', 'rules'=>''),
	    ));
	    if($this->form_validation->run()==TRUE){
	        $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
	        $newObj->pay_time = strtotime($newObj->pay_time);
	        
	        $redirectUrl = site_url($this->_thisModule.$this->_thisController.'/add/?'.http_build_query($newObj));
	        $userInfo = IOSS_User::getByAccount($newObj->account);
	        //验证账号
	        if(!$userInfo){
	            errorAndRedirect('用户账号未找到！',$redirectUrl);
	        }
	        //验证银行卡编号
	        $this->load->model('MBankInfo');
	        $bankInfo = $this->MBankInfo->getByCode($newObj->bank_code);
	        if(!$bankInfo){
	            errorAndRedirect('自有通道编号不存在！',$redirectUrl);
	        }
	        //事务处理：创建order表订单记录，返回order_id后，处理插入selfbank_order
	        $this->db->trans_start();
	        $order = $this->MOrder->createOrderFromSelfBank($userInfo->id,$newObj->recharge_amount,$newObj->bank_code,$newObj->pay_time,$newObj->pay_transaction,1);
	        if(!$order){
	            $this->db->_trans_status = FALSE;
	        }
	        
	        $time = time();
	        $newObj->create_time = $time;
	        $newObj->update_time = $time;
	        $newObj->order_no = $order['no'];
	        $newObj->user_id = $userInfo->id;
	        
	        if(!$this->MSelfBankOrder->create($newObj)){
	            $this->db->_trans_status = FALSE;
	        }
	        $this->db->trans_complete();
	        if($this->db->trans_status() == FALSE){
	            errorAndRedirect('创建手工订单失败！',$redirectUrl);
	        }
	        //记录订单表操作日志
	        $this->MOrder->log($order['id'],IOSS_Order::PAY_STATE_PAID,IOSS_Order::PAY_STATE_NOT_RECHARGED,'手工创建订单');
	        successAndRedirect('手工创建订单成功！');
	    }
	    $this->assign('obj', $obj);
	    $this->layout();
	}
	
	/**
	 * 检查账号是否存在 
	 * @param string $account 账号
	 */
	function _checkAccount($account){
	    $userInfo = IOSS_User::getByAccount($account);
	    if(!$userInfo){
	        $this->form_validation->set_message('_checkAccount', '提交的用户账号不存在！');
	        return false;
	    }
	    return true;
	}
	/**
	 * 检查银行卡编号是否存在 
	 * @param string $code 银行编号  
	 */
	function _checkBankCode($code){
	    $this->load->model('MBankInfo');
	    $bankInfo = $this->MBankInfo->getByCode($code);
	    if(!$bankInfo){
	        $this->form_validation->set_message('_checkBankCode', '提交自有通道编号不存在！');
	        return false;
	    }
	    return true;
	}
	
	function view($id){
	       
	    if(!$this->p->edit){
	        //权限不足
	        show_error(l('user_has_nopower'));
	    }
		if(!is_numeric($id)){
			show_error(l('id_not_null'));
		}
		$obj = $this->MOrder->getOne(Array('id'=>$id));
		if(!$obj){
			errorAndRedirect('未找到定义！');
		}
		$this->load->model('MOrderLog');
		$orderLogList = $this->MOrderLog->getAll(Array('order_id'=>$id));
		$this->load->model('MUser');
		$userInfo = $this->MUser->getOne(array('id'=>$obj->user_id));
		$this->load->model('MPaymentConfig');
		$paymentType = $this->MPaymentConfig->getByCode($obj->pay_channel);
		$this->assign('order', $obj);
		$this->assign('paymentType', $paymentType);
		$this->assign('orderLogList', array_reverse($orderLogList));
		$this->assign('userInfo', $userInfo);
		$this->layout('view');
	}
	
	function recharge($id,$update_time){
		if(!is_numeric($id) || !is_numeric($update_time)){
			show_error(l('id_not_null'));
		}
		$redirectUrl = site_url($this->_thisModule.$this->_thisController.'/view/'.$id);
		$order = $this->MOrder->getOne(Array('id'=>$id));
		if(!$order){
			errorAndRedirect('未找到定义！',$redirectUrl);
		}
		if($update_time != $order->update_time){
			errorAndRedirect('操作冲突，请重试', $redirectUrl);
		}
		if ($order->pay_status != IOSS_Order::PAY_STATE_PAID || $order->transfer_status != IOSS_Order::PAY_STATE_NOT_RECHARGED){
			//订单状态为必须是已付款、未充值才可以进行充值操作
			errorAndRedirect('订单状态不正确', $redirectUrl);
		}
		
		//调用充值接口给游戏充值----------------------------------------------
		$user = IOSS_User::getById($order->user_id);
		$billno = date('ymdHis') . rand(1000,9999);
		// 预转账
		if(!IOSS_AGApi::agin_prepare_transfer_credit($user->account, $user->game_key, $billno, 'IN', $order->amount, $prepare_error_message)){
		    errorAndRedirect('平台预操作失败', $redirectUrl); // 预转账失败
		}
		// 转账确认
		if (!IOSS_AGApi::agin_confirm_transfer_credit($user->account, $user->game_key, $billno, 'IN', $order->amount, $confirm_error_message)){
		    if ($confirm_error_message['Type'] === 'network_error') {
		        if (!IOSS_AGApi::agin_query_transfer_status($billno, $query_error_message)) {
		            errorAndRedirect('平台操作状态确认未成功', $redirectUrl);
		        }
		    }else{
		        errorAndRedirect('平台操作失败', $redirectUrl);;
		    }
		}
		//--------------------------------------------------------------
		
		//修改订单状态
		$time = time();
		$order->transfer_status = IOSS_Order::PAY_STATE_RECHARGED;
		$order->transfer_time = $time;
		if(!$this->MOrder->update($order)){
			errorAndRedirect('修改订单状态失败', $redirectUrl);
		}
		//操作日志添加记录
		$this->load->model('MOrderLog');
		$newLog = new stdClass();
		$newLog->order_id = $order->id;
		$newLog->pay_status = $order->pay_status;
		$newLog->transfer_status = $order->transfer_status;
		$newLog->admin_id = $this->_user->id;
		$newLog->admin_account = $this->_user->account;
		$newLog->admin_name = $this->_user->name;
		$newLog->note = '【客服手动转入平台操作】';
		$newLog->create_time = $time;
		$this->MOrderLog->add($newLog);
		successAndRedirect('平台操作确认成功',$redirectUrl);		
	}
	
	function delete($id, $update_time){
		if(!is_numeric($id) || !is_numeric($update_time)){
			show_error(l('id_not_null'));
		}
		$this->load->model('MGameTags');
		
		$this->db->trans_start();
		if(!$this->MGame->delete($id, $update_time)){
			$this->db->_trans_status = FALSE;
		}
		if(!$this->MGameTags->deleteGameId($id)){
			$this->db->_trans_status = FALSE;
		}
		$this->db->trans_complete();
		if($this->db->trans_status()!==FALSE){
			successAndRedirect(l('delete_success'));
		}else{
			errorAndRedirect(l('data_fail'));
		}
		
	}
	
	
}